package com.code.translate.utils;

import org.springframework.core.io.ClassPathResource;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

/**
 * @author ggh
 * @date 2022/7/8
 */
public class JSUtils {
    public static Object execute(String filepath, String func, Object... objs) {
        try {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("javascript");

            ClassPathResource resource = new ClassPathResource(filepath);
            engine.eval(IOUtils.readInputStream(resource.getInputStream()));
            if (engine instanceof Invocable) {
                Invocable invoke = (Invocable) engine; // 调用merge方法，并传入两个参数
                Object result = invoke.invokeFunction(func, objs);
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
